package org.zk.dubbo_consumer.secutity;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.LoggerFactory;
import org.zk.entity.Teacher;
import org.zk.entity.User;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * 限制并发人数登陆
 */
public class KickoutSessionControlFilter extends AccessControlFilter {


    private static org.slf4j.Logger logger = LoggerFactory.getLogger(KickoutSessionControlFilter.class);

    private String kickoutUrl;//踢出出后到的地址
    private boolean kickoutAfter = false;//踢出之前登录的/之后登录的用户，false代表默认踢出之前登录的用户，true代表踢出之后登录的用户
    private int maxSession = 1;//同一账号最大回话数，默认1

    private SessionManager sessionManager;
    private Cache<String, Deque<Serializable>> cache;

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    //设置Cache的key的前缀
    public void setCache(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro_redis_cache");
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {




        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            //如果没有登录，直接进行之后的流程
            return true;

        }
//        以下是登录 ------------------------------------------------------------------------------------------
        Session session = subject.getSession();
        String phone="";
        Serializable sessionId="";
       try{
           if (getLoginUrl().equals("/teacherIndex2") || getLoginUrl().equals("/static/js/gs/layui-v2.5.5/layui/lay/modules/theme/default/laydate.css")) {
               Teacher teacher= (Teacher) session.getAttribute("teacher");
//            Teacher teacher= (Teacher) subject.getPrincipals();
               phone=teacher.getTeacherPhone();
               sessionId=session.getId();
           }else {
               User user = (User) subject.getPrincipal();
               phone = user.getUserPhone();
               sessionId = session.getId();
           }
       }catch (Exception e){

       }
        //读取缓存  没有就存入
        Deque<Serializable> deque = cache.get(phone);

        //如果此用户没有session队列，也就是还没有登录过，缓存没有
        //就new一个空队列，不然deque对象为空，会报空指针
        if (deque == null) {
            deque = new LinkedList<Serializable>();
        }


        //这个人没有登陆过，如果队列里没有此sessionId,且用户没有被踢出，放入队列
        if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            //将sessionId存入队列
            deque.push(sessionId);
            //将用户的sessionId队列缓存
            cache.put(phone, deque);
        }


        //这个人已经登陆过了，如果队列里的sessionId数超出最大回话数，开始踢人
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            if (kickoutAfter) {//如果踢出后者
                kickoutSessionId = deque.removeFirst();
                //提出后再更新下缓存队列
                cache.put(phone, deque);
            } else {//否则踢出前者
                kickoutSessionId = deque.removeLast();
                //踢出后再更新下缓存队列
                cache.put(phone, deque);
            }

            try {
                //获取被踢出的sessionId的session对象
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if (kickoutSession != null) {
                    //设置回话的kickout属性表示踢出了
                    kickoutSession.setAttribute("kickout", true);
                }
            } catch (Exception e) {//忽略异常
            }
        }


        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute("kickout") != null) {
            //会话被踢出
            try {
                //退出登录
                subject.logout();
            } catch (Exception e) {//忽略异常
            }

            saveRequest(request);

            Map<String, String> resultMap = new HashMap<String, String>();
            //判断是不是Ajax请求
            if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
                resultMap.put("user_status", "300");
                resultMap.put("message", "您已经在其他地方登录，请重新登录！");
                //输出json串
                out(response, resultMap);
            } else {
                //重定向
                WebUtils.issueRedirect(request, response, kickoutUrl);
            }
            return false;
        }
        return true;
    }
    //        以上是登录 ------------------------------------------------------------------------------------------
    private void out(ServletResponse response, Map<String, String> resultMap) {

        try {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.println(JSON.toJSONString(resultMap));
            out.flush();
            out.close();
        } catch (Exception e) {
            System.err.println("KickoutSessionFilter.class 输出JSON异常，可以忽略。");
        }
    }
}
